package com.leyou.item.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.constants.RedisConstants;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <h3>leyou-project</h3>
 * <p></p>
 *
 * @author : hhw
 * @date : 2020-05-24 10:45
 **/
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public List<Brand> queryBrandsByCategoryId(Long id) {
        /**
         * 1.根据分类Id查询中间表得到品牌id集合
         * 2.根据品牌Id集合查询
         */
        return listByIds(categoryBrandService
                .query()
                .eq("category_id", id)
                .list()
                .stream()
                .map(CategoryBrand::getBrandId)
                .collect(Collectors.toList()));
    }

    @Override
    @Transactional    //事务管理
    public void saveBrand(BrandDTO brandDTO) {

        /**
         * 1.将品牌插入,并返回brandId值
         * 2.将brandId值和categoryIds逐条插入中间表
         */
        Brand brand = brandDTO.toEntity(Brand.class);
        boolean flag = save(brand);
        if(!flag) {
            throw  new LyException(500, "新增品牌失败");
        }
        flag = categoryBrandService.saveBatch(brandDTO
                .getCategoryIds()
                .stream()
                .map(id -> CategoryBrand.of(id, brand.getId()))
                .collect(Collectors.toList()));
        if(!flag) {
            throw  new LyException(500, "新增品牌分类中间表失败");
        }
        stringRedisTemplate.opsForSet().add(RedisConstants.BRAND_PIC_DB_RESOURCE, brand.getImage());
    }

    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {
        /**
         * 1.根据brandId更新brand
         * 2.根据brandId删除
         * 3.新增分类品牌集合
         */
        Brand brand = brandDTO.toEntity(Brand.class);
        String image = getById(brand.getId()).getImage();
        boolean flag = updateById(brand);
        if (!flag) {
            throw new LyException(500, "更新品牌失败");
        }

        flag = categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", brand.getId()));
        if (!flag) {
            throw new LyException(500, "根据品牌id删除中间表失败");
        }

        flag = categoryBrandService.saveBatch(brandDTO
                .getCategoryIds()
                .stream()
                .map(id -> CategoryBrand.of(id, brand.getId()))
                .collect(Collectors.toList()));
        if (!flag) {
            throw new LyException(500, "根据品牌id更新中间表失败");
        }
        stringRedisTemplate.opsForSet().add(RedisConstants.BRAND_PIC_DB_RESOURCE, brand.getImage());
        stringRedisTemplate.opsForSet().remove(RedisConstants.BRAND_PIC_DB_RESOURCE,image);
    }

    @Override
    public PageDTO<BrandDTO> pageQuery(String key, Integer page, Integer rows) {
        /**
         * 获取分页数据
         * 获取总条数,以及总页数
         * 封装置pageDTO返回
         */
        Page<Brand> brandPage = query().eq(StringUtils.isNotEmpty(key), "letter", key)
                .or()
                .like(StringUtils.isNotEmpty(key), "name", key)
                .page(new Page<Brand>().setCurrent(Math.max(1, page)).setSize(Math.max(5, rows)));
        long total = brandPage.getTotal();
        long totalPages = brandPage.getPages();
        List<Brand> brands = brandPage.getRecords();
        List<BrandDTO> brandDTOS = BrandDTO.convertEntityList(brands);
        return new PageDTO<BrandDTO>(total, totalPages, brandDTOS);


    }

    @Override
    @Transactional
    public void removeByBrandId(Long id) {
        /**
         * 查找id品牌对应的image
         * 因为有中间表,所以必须先删除中间表
         * 再删除品牌表
         */
        Brand brand = getById(id);
        String image = brand.getImage();
        boolean flag = categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", id));
        if (!flag) {
            throw new LyException(500, "根据品牌id删除中间表失败");
        }
        flag = removeById(id);
        if (!flag) {
            throw new LyException(500, "根据id删除品牌失败");
        }
        stringRedisTemplate.opsForSet().remove(RedisConstants.BRAND_PIC_DB_RESOURCE,image);
    }
}
